{% extends 'base.html' %}
{% load static %}
{% block css %}
<link rel="stylesheet" type="text/css" href="{% static 'assets/select2/select2.css' %}" />
    <style>
        #editor {width: 100%;height: 300px;}
        .host-link {margin-top: 10px}
        .host-link .host-tags {margin-right: 5px;cursor: pointer}
        .btn-exchange{height: 41px}
        #name{height: 41px}
    </style>
{% endblock %}
{% block title %}
    添加配置任务
{% endblock %}
{% block page-title %}
    添加配置任务
{% endblock %}
{% block page-content %}
    <div class="row">
        <div class="col-lg-12">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title">添加配置任务</h3>
                </div>
                <div class="panel-body">
                    {% if messages %}
                        {% for message in messages %}
                            <div class="alert alert-{{ message.tags }} alert-dismissable">
                                <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                                {{ message }}
                            </div>
                        {% endfor %}
                    {% endif %}
                      <form class="form-horizontal" role="form" action="" method="post">
                               <div class="form-group">
                                <label class="col-sm-2 control-label">配置文件类型:</label>
                                <div class="col-sm-10">
                                    <select data-placeholder="请选择一种类型" name="type" id="type" class="select2" tabindex="4">
                                        {% for type in types %}
                                            <option value="{{ type.0 }}">{{ type.1 }}</option>
                                        {% endfor %}
                                    </select>
                                </div>
                            </div>

                            <div class="form-group">
                                <label class="col-sm-2 control-label">任务名称:</label>
                                <div class="col-sm-10">
                                    <div class="input-group task-ele">
                                        {% if tasks %}
                                            <select data-placeholder="请选择一个任务" name="name" id="name" class="select2">
                                            <option value="" selected></option>
                                                {% for task in tasks %}
                                                    <option value="{{ task.name }}">{{ task.name }}</option>
                                                {% endfor %}
                                            </select>
                                            <span class="input-group-btn">
                                                <button type="button" class="btn btn-primary btn-exchange">添加</button>
                                            </span>
                                        {% else %}
                                            <input type="text" name="name" id="name" class="form-control" autocomplete="off"/>
                                             <span class="input-group-btn">
                                                <button type="button" class="btn btn-primary">添加</button>
                                            </span>
                                        {% endif %}
                                    </div>
                                    <span class="help help-block">如果任务名称存在则选择，不存在则点击右边的按钮进行添加！</span>
                                </div>
                            </div>

                             <div class="form-group">
                                <label class="col-sm-2 control-label">配置文件内容:</label>
                                <div class="col-sm-10">
                                    <div id="editor"></div>
                                    <span class="help help-block">Nginx配置文件日志文件目录名称和server_name域名保持一致！</span>
                                </div>
                            </div>

                            <div class="form-group">
                                <label class="col-sm-2 control-label">目标主机:</label>
                                <div class="col-sm-10">
                                    <select data-placeholder="请选择一或多个主机" name="dest_hosts" id="dest_hosts" class="select2 " multiple tabindex="4">
                                        {% for host in hosts %}
                                            <option value="{{ host.id }}">{{ host.instance_name }}</option>
                                        {% endfor %}
                                    </select>
                                    <div class="host-link">
                                        {% for tag in tags %}
                                            <span class="label label-default host-tags" data-name="{{ tag.name }}">{{ tag.name_cn}}</span>
                                        {% endfor %}
                                    </div>
                                </div>
                            </div>

                            <div class="form-group">
                                <label class="col-sm-2 control-label">目标路径:</label>
                                <div class="col-sm-10">
                                    <input type="text" name="dest_dir" id="dest_dir" class="form-control">
                                    <span class="help help-block"><ul>
                                        <li>文件的绝对路径，包括文件名称,例如：/usr/local/openresty/nginx/conf/vhosts/www.miaoshou.net.conf</li>
                                        <li>Nginx配置文件名称必须使用 域名+ .conf，并且域名和配置文件内容中server_name域名保持一致</li>
                                    </ul></span>
                                </div>
                            </div>

                            <div class="form-group">
                                <div class="col-sm-4 col-sm-offset-2">
                                    <button class="btn btn-primary btn-test" type="button" name="_test" title="测试配置文件语法是否正确">测试</button>
                                    <button class="btn btn-primary btn-submit" type="button" name="_save">提交</button>
                                    <button class="btn btn-white" type="reset">取消</button>
                                </div>
                            </div>
                      </form>
                </div>
            </div>
        </div>
    </div>
{% endblock %}
{% block modal %}
<div class="modal inmodal fade" id="test_result" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span
                        class="sr-only">Close</span></button>
                    <h4 class="modal-title">配置文件测试结果</h4>
                </div>
                <div class="modal-body">
                    <pre id="content"></pre>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-info" data-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>
{% endblock %}
{% block js %}
    <script src="{% static 'ace/src/ace.js' %}" type="text/javascript" charset="utf-8"></script>
    <script src="{% static 'ace/src/theme-chrome.js' %}" type="text/javascript" charset="utf-8"></script>
    <script src="{% static 'ace/src/mode-nginx.js' %}"></script>
    <script src="{% static 'ace/src/ext-language_tools.js' %}"></script>
    <script src="{% static 'assets/select2/select2.min.js' %}" type="text/javascript"></script>
    <script>
        jQuery(".select2").select2({
            width: '100%'
        });
    </script>
    <script>
        var editor = ace.edit("editor");
            //字体大小
            editor.setTheme('ace/theme/chrome');
            editor.session.setMode('ace/mode/nginx');
            editor.setFontSize(18);
            //设置只读（true时只读，用于展示代码）
            editor.setReadOnly(false);
            //自动换行,设置为off关闭
            editor.setOption("wrap", "free");
            //启用提示菜单
            editor.setOptions({
                    enableBasicAutocompletion: true,
                    enableSnippets: true,
                    enableLiveAutocompletion: true,
                });

    </script>
     <script>
        //改变ace editor的模式，使不同的配置文件内容高亮
        function changeMode(type){
            if(type === 'nginx'){
                    editor.session.setMode('ace/mode/nginx')
                }else if(type === 'es'){
                    editor.session.setMode('ace/mode/yaml')
                }else{
                    editor.session.setMode('ace/mode/ini')
                }
        }
        //通过task type获取对应类型的任务并渲染
        function getTasksByType(type){
            $.ajax({
                type: 'GET',
                url: '/tasks/get_tasks_by_type/',
                data: {type: type},
                success: function (result) {
                    var parentNode = $('.task-ele');
                    if(result.length === 0){
                        parentNode.empty();
                        parentNode.append('<input type="text" name="name" id="name" class="form-control" autocomplete="off"><span class="input-group-btn"><button type="button" class="btn btn-primary btn-add">添加</button></span>');
                        $('.btn-add').css('height', '41px');
                        editor.setValue('');
                        $("#dest_hosts").val("");
                        $('#dest_dir').val("");
                    }else{
                        parentNode.empty();
                        var select_str = '<select data-placeholder="请选择一个任务" name="name" id="name" class="select2">';
                        var options_str = '<option value="" selected></option>';
                        $.each(result, function (index, value) {
                           options_str += '<option value="' + value['fields']['name'] + '">' + value['fields']['name'] + '</option>'
                        });
                        var tasks_str = select_str + options_str + '</select>' + '<span class="input-group-btn"><button type="button" class="btn btn-primary btn-exchange">添加</button></span>';
                        parentNode.append(tasks_str);
                        $('#name').select2({width: '100%'});
                        $('.btn-exchange').css('height', '41px');
                    }
                }
            })
        }
        //监听配置文件类型改变事件
        $('#type').on('change', function (event, params) {
            var type = $(this).val();
            changeMode(type);
            getTasksByType(type);
            editor.setValue('');
            $("#dest_hosts").val("");
            $('#dest_dir').val("");
        });
    </script>
    <script>
        function initHost() {
            var host_options = '';
            var dest_hosts = $('#dest_hosts');
            dest_hosts.empty();
            {% for host in hosts %}
                host_options += "<option value='" + {{ host.id }} + "'>" + '{{ host.instance_name }}' + "</option>";
            {% endfor %}
            dest_hosts.html(host_options)
        }
        //因为任务名称的元素都是动态生成的，包括‘选择’，‘添加’按钮，动态生成后又的重新绑定
        //按钮点击事件，所以给按钮的父元素绑定点击事件，但是监听的还是按钮，这样就决绝了动态
        //生成的按钮需要重新绑定监听事件的问题。
        //监听任务名称右边的按钮点击事件
        $('.task-ele').on('click', '.btn-exchange' ,function () {
            var btn_text = $(this).text();
            if(btn_text === '选择'){
                var type = $('#type').val();
                getTasksByType(type);
            }else {
                var parentNode = $('.task-ele');
                parentNode.empty();
                parentNode.prepend('<input type="text" name="name" id="name" class="form-control" autocomplete="off"><span class="input-group-btn"><button type="button" class="btn btn-primary btn-exchange">选择</button></span>')
            }
        });
        //监听任务名称选择框改变事件
        $(".task-ele").on('change', '#name', function () {
            var task_name = $('#name').val();
            var type = $('#type').val();
            changeMode(type);
            $.ajax({
                type: 'GET',
                url: '/tasks/get_task_info/',
                data: {'task_name': task_name},
                success: function (result) {
                    console.log(result);
                    if(result['code'] === 0){
                        var task = result['data'][0];
                        editor.setValue(task['fields']['content']);
                        $('#dest_dir').val(task['fields']['dest_dir']);
                        var dest_hosts = task['fields']['dest_hosts'];
                        $('#dest_hosts').val(dest_hosts).change();
                        {#$("#type").val(task['fields']['type']).change();#}
                    }else if(result['code'] === 2){
                        swal({
                            title: '警告',
                            text: result['msg'],
                            type: 'warning'
                        });
                        return false
                    }
                }
            })
        });
        //监听点击主机标签事件
        $('.host-tags').click(function () {
            var tag = $(this).text();
            $.ajax({
                type: 'GET',
                url: '/assets/get_host_by_tag?tag=' + tag,
                success: function (result) {
                    if (result['code'] === 0) {
                        var dest_hosts = $('#dest_hosts');
                        var selected_hosts = [];
                        var data = dest_hosts.select2('data');
                        $.each(data, function (index, value) {
                           selected_hosts.push(parseInt(value['id']))
                        });
                        var hosts = result['hosts'];
                        var all_selected_hosts = selected_hosts.concat(hosts);
                        var set = new Set(all_selected_hosts);
                        all_selected_hosts = [...set];
                        dest_hosts.val(all_selected_hosts).change();
                    }
                }
            })
        });
        //监听提交按钮点击事件
        $('.btn-submit').click(function () {
            var data = $('form').serializeArray();
            var content = editor.getValue();
            data.push({name: 'content', value: content});
            $.ajax({
                type: 'POST',
                url: '/tasks/add/',
                data: data,
                beforeSend: function (xhr, settings) {
                     xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
                },
                success: function (result) {
                    if(result['code'] === 0){
                        window.location.href = '/tasks/';
                    }
                }
            })
        });

        function get_task_result(modal, task_id) {
            $.ajax({
                type: "GET",
                url: "/tasks/get_task_result/?task_id=" + task_id + '&type=test',
                success: function (result) {
                    modal.find('.modal-body #content').text(result['data']);
                }
            })
        }
        //监听测试按钮
        $('.btn-test').click(function () {
            var type = $('#type').val();
            var content = editor.getValue();
            var ids = [];
            var data = $('#dest_hosts').select2('data');
            $.each(data, function (index, value) {
                ids.push(parseInt(value['id']))
            });
            var dest_dir = $('#dest_dir').val();
            $.ajax({
                type: 'POST',
                url: '/tasks/config_test/',
                data:{type: type, content: content, ids: JSON.stringify(ids), dest_dir: dest_dir},
                beforeSend: function (xhr, settings) {
                     xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
                },
                success: function (result) {
                    var task_id = result['task_id'];
                    var modal = $('#test_result');
                    modal.modal('show');
                    get_task_result(modal, task_id);
                    var t1 = setInterval(get_task_result, 1000, modal, task_id);
                        // 10秒后清除定时器
                    setTimeout(clearInterval, 10000, t1)
                }
            })
        })
    </script>
    <script>
        $('.task').addClass('active');
        $('.task .task-add').addClass('active');
    </script>
{% endblock %}